from ..database import database, TABLE_PREFIX, ModelMixin
from peewee import *
from .currency import Currency
import datetime
from playhouse.signals import pre_save, Model
from flask_pw.models import Model as Model_


class Account(database.Model, Model, ModelMixin):
    id = CharField(primary_key=True, max_length=60)
    # member = ForeignKeyField(Member, help_text='所属用户')
    currency = ForeignKeyField(Currency, help_text='币种')
    balance = DecimalField(db_column='balance', decimal_places=4, default=0.00, help_text='balance')
    frozen_amount = DecimalField(db_column='frozen_amount', decimal_places=4, help_text='冻结金额', default=0.00)
    pending_amount = DecimalField(db_column='pending_amount', decimal_places=4, help_text='待结算金额', default=0.00)
    status = CharField(db_column='status', max_length=10, default='normal')
    remark = CharField(db_column='remark', max_length=300, default='')
    updated_at = DateTimeField(db_column='updated_at', help_text='更新时间', default=datetime.datetime.now)
    created_at = DateTimeField(db_column='created_at', help_text='创建时间', default=datetime.datetime.now)
    reward_amount = DecimalField(db_column='reward_amount', help_text='奖励金额', decimal_places=4, default=0.00)

    # class Meta:
    #     db_table = '{}_accounts'.format(TABLE_PREFIX)

    @classmethod
    def get_by_member(cls, member):
        return cls.get_or_none(Account.member == member)


    # class Meta:
    #     db_table = '{}_account_his'.format(TABLE_PREFIX)

# @Account.pre_save
# def account_pre_save_handler(instance, created):
#     if created:
#         if hasattr(instance, '_meta'):
#             meta = getattr(instance, '_meta')
#             fields = meta.fields
#             id = fields.get('id')
#             if isinstance(id, CharField) and id.primary_key:
#                 from .table_seq import TableSeq
#                 code = getattr(meta, 'db_table') or 'account'
#                 next_id = TableSeq.get_seq(code)
#
#                 instance.id = '{}{}'.format(instance.currency.id, str(next_id).zfill(24))
